import userService from '@/api/modules/user'
import { cookies } from '@/utils/cookie'
import { storage } from '@/utils/storage'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {
  const token = ref(storage.get('token') ?? '')
  const userInfo = ref(storage.get('userInfo') ?? {})

  const authFormVisible = ref(false)
  const authFormType = ref('login')

  function setToken(newToken) {
    return new Promise((resolve) => {
      token.value = newToken
      storage.set('token', newToken)
      cookies.set('tradeMallMall_token', newToken)
      resolve(true)
    })
  }

  async function getUserInfo() {
    try {
      const res = await userService.getUserInfo()
      userInfo.value = res.user
      storage.set('userInfo', res.user)
      return res.user
    }
    catch (error) {
      return null
    }
  }

  function logout() {
    token.value = ''
    userInfo.value = {}
    storage.remove('token')
    storage.remove('userInfo')
    cookies.delete('tradeMallAdmin_token')
  }

  function toggleAuthFormModal(visible,type) {
    authFormVisible.value = visible
    authFormType.value = type
  }

  return {
    token,
    userInfo,
    getUserInfo,
    logout,
    setToken,
    authFormVisible,
    authFormType,
    toggleAuthFormModal,
  }
})
